<template>
	<div class="evidence-unit-evidenceDetails-container" :style="[{ 'overflow-x': 'hidden' }, { height: screenHeight + 'px' }]">
		<el-card shadow="hover" body-style="padding:8px; ">
			<div class="card-header" style="width: 100%; margin-top: 5px; border-top: 1px solid AliceBlue">
				<el-row justify="end" style="margin-bottom: 15px; margin-top: 3px">
					<el-col :span="8">
						<div style="float: left; height: 40px; width: 5px; background: green"></div>
						<div style="float: left; margin-top: 10px; margin-left: 20px; font-size: 16px">案件信息</div>
					</el-col>
					<el-col :span="16" style="text-align: right">
						<el-button type="primary" icon="el-icon-edit" @click="onEditCaseInfo" size="mini" v-if="isSameOrgan">编辑案件信息</el-button>
						<el-button type="primary" @click="onUploadFile" size="mini"><i class="el-icon-upload el-icon--left"></i>附件</el-button>
						<el-button type="primary" icon="el-icon-check" @click="pandian" size="mini" v-if="isSameOrgan">盘点</el-button>
						<el-button type="primary" icon="el-icon-printer" @click="onPrintCaseInfo" size="mini" v-if="isSameOrgan">打印案件标签</el-button>
					</el-col>
				</el-row>
				<ShowCase :formInline="formInlineCase" />
			</div>
			<div class="card-header" style="width: 100%; margin-top: 5px; border-top: 1px solid AliceBlue">
				<el-row justify="end" style="margin-bottom: 15px; margin-top: 3px">
					<el-col :span="8">
						<div style="float: left; height: 40px; width: 5px; background: green"></div>
						<div style="float: left; margin-top: 10px; margin-left: 20px; font-size: 16px">案卷列表</div>
					</el-col>
					<el-col :span="16" style="text-align: right">
						<el-button type="primary" icon="el-icon-edit" @click="onAddEvidenceInfo" size="mini"  v-if="isSameOrgan">新增案卷</el-button>
						<el-button type="primary" icon="el-icon-delete" @click="onDelete" size="mini"  v-if="isSameOrgan">删除案卷</el-button>
						<el-button type="primary" icon="el-icon-bottom" @click="onEviInInfo" size="mini"  v-if="isSameOrgan">入库</el-button>
						<el-button type="primary" icon="el-icon-top" @click="onEviOutInfo" size="mini"  v-if="isSameOrgan">出库</el-button>
						<el-button type="primary" icon="el-icon-rank" @click="onEviChangeInfo" size="mini"  v-if="isSameOrgan">更换位置</el-button>
						<el-button type="primary" icon="el-icon-printer" @click="onPrintEviInfo" size="mini"  v-if="isSameOrgan">打印案卷标签</el-button>
					</el-col>
				</el-row>
				<el-table
					ref="refEvidenceGrid" border
					:data="tableData"
					:default-sort="{ prop: 'name', order: 'descending' }"
					:row-style="{ height: '0' }"
					:cell-style="{ padding: '0' }"
					size="medium"
					style="width: 100%"
					max-height="300"
					highlight-current-row
					@row-click="rowClick"
					@selection-change="handleEvidenceSelectionChange"
				>
					<el-table-column align="center" type="selection" width="55" />
					<el-table-column align="center" label="序号" type="index" width="60"> </el-table-column>
					<el-table-column align="center" text-align="right" property="no" width="250" sortable label="案卷编号" show-overflow-tooltip>
						<template #default="scope">
							<el-tag v-if="scope.row.rfid=='-1'" type="success" :title="scope.row.rfid" style="margin-right: 5px">epc</el-tag>
							<el-tag v-else-if="scope.row.rfid=='-2'" type="info" style="margin-right: 5px">epc</el-tag>
							{{ scope.row.no }}
						</template>
					</el-table-column>
					<el-table-column align="center" sortable label="案卷名称/数量" show-overflow-tooltip>
						<template #default="scope">{{ `${scope.row.name}/${scope.row.quantity}` }}</template>
					</el-table-column>
									<el-table-column align="center" property="extractionDateTime" sortable label="办理时间" show-overflow-tooltip>
					<template #default="scope">{{ dateFormat(scope.row.extractionDateTime) }}</template>
				</el-table-column>
					<el-table-column align="center" property="source" sortable label="经办人" show-overflow-tooltip />
				<el-table-column align="center" property="extractionPersonName" sortable label="保管单位" show-overflow-tooltip />

					<!-- <el-table-column align="center" property="extractMethod" sortable label="案卷来源" show-overflow-tooltip /> -->
					<el-table-column align="center" property="status" sortable label=" 案卷状态" show-overflow-tooltip>
						<template #default="scope">{{ `${getEvidenceStatus(scope.row.status) ?? '未知'}` }}</template>
					</el-table-column>
					<el-table-column align="center" property="location" sortable label="位置" show-overflow-tooltip />
					<el-table-column align="center" label="操作" width="365px">
						<template #default="scope">
							<!-- <el-button type="primary" plain size="mini" @click="onReaderInfo(scope.row)">读卡</el-button> -->
							<!--<el-button :type="scope.row.xingHao?'success':'info'" plain size="mini" @click="view3D(scope.row)" >3D模型</el-button>-->
							<el-button type="success" plain size="mini" @click="onEditEvidenceInfo(scope.row)" v-if="isSameOrgan">编辑</el-button>
							<el-button type="success" plain size="mini" @click="onEviImgInfo(1, scope.row)">照片</el-button>
							<el-button type="success" plain size="mini" @click="onUploadFile(1, scope.row)">附件</el-button>
						</template>
					</el-table-column>
				</el-table>
			</div>
			<div class="card-header" style="width: 100%; margin-top: 15px; border-top: 1px solid AliceBlue">
				<el-row>
					<div style="height: 40px; width: 5px; background: green"></div>
					<div style="margin-top: 10px; margin-left: 20px; font-size: 16px">{{ title }}</div>
				</el-row>
				<el-table
					ref="multipleTable"
					:data="tableLogData"
					:default-sort="{ prop: 'name', order: 'descending' }"
					:row-style="{ height: '35px' }"
					:cell-style="{ padding: '0' }"
					size="medium"
					style="width: 100%"
				>
					<el-table-column align="center" label="序号" type="index" width="60"> </el-table-column>
					<el-table-column align="center" prop="deliveryNo" width="180" sortable label="流转单号" show-overflow-tooltip>
						<template #default="scope">
							<el-link :underline="false" @click="onLink(scope.row,false)" type="primary">{{ scope.row.deliveryNo }} </el-link></template
						>
					</el-table-column>
					<el-table-column align="center" prop="deliveryTime" sortable label="交接时间" show-overflow-tooltip>
						<template #default="scope">{{ `${dateFormats(scope.row.deliveryTime, 'yyyy-MM-DD HH:mm')}` }}</template>
					</el-table-column>
					<el-table-column align="center" property="caseOrg" sortable label="移交人/移交电话" show-overflow-tooltip>
						<template #default="scope">{{ `${scope.row.transferor}/${scope.row.transferorPhone}` }}</template>
					</el-table-column>
					<el-table-column align="center" property="receiver" sortable label="接收人" show-overflow-tooltip />
					<el-table-column align="center" property="remark" sortable label="原因" show-overflow-tooltip />
					<el-table-column align="center" property="deliveryDicTypeName" sortable label="状态" show-overflow-tooltip />
					<el-table-column align="center" label="操作" width="170px">
						<template #default="scope">
							<el-button type="primary" @click="onEviImgInfo(3, scope.row)" plain size="mini">凭证</el-button>
							<el-button type="success" @click="onInventoryInfo(scope.row)" plain size="mini">交接清单</el-button>
						</template>
					</el-table-column>
				</el-table>
			</div>
		</el-card>
		<CasePrint ref="casePrintRef" />
		<EditCase ref="editCaseRef" :formInline="refFormInlineCase" @reload="init" :isSameOrgan="isSameOrgan" />
		<EditEvi ref="editEviRef" :caseId="caseid" @reload="init" :isSameOrgan="isSameOrgan" />
		<EviPrint ref="eviPrintRef" @reload="init" />
		<!-- <EviChangeLoc ref="eviChangeRef" :selectionEvidences="selectionEvidences" @reload="init" /> -->
		<InInventory ref="InInventoryRef" />
		<ChangeInventory ref="ChangeInventoryRef" />
		<OutInventory ref="OutInventoryRef" />
		<el-drawer v-model="drawer" title="选择位置 " direction="rtl" size="80%" destroy-on-close>
			<store-index :isShow="1" :isInOut="1" :height="0" />
		</el-drawer>
	</div>
</template>
<script lang="ts">
import { ref, toRefs, reactive, defineComponent, getCurrentInstance, onUnmounted } from 'vue';
import { useRouter } from 'vue-router';
import { useStore } from '/@/store/index';
import CasePrint from '/@/views/evidence/unit/component/casePrint.vue';
import EditCase from '/@/views/evidence/unit/component/editCase.vue';
import EditEvi from '/@/views/evidence/unit/component/editEvi.vue';
import EviPrint from '/@/views/evidence/unit/component/eviPrint.vue';
import InInventory from '/@/views/evidence/unit/component/inInventory.vue';
import ChangeInventory from '/@/views/evidence/unit/component/changeInventory.vue';
import OutInventory from '/@/views/evidence/unit/component/outInventory.vue';
import ShowCase from '/@/views/evidence/unit/component/showCase.vue';
import { getCaseEvidence, checkEvidenceAuditState ,savePanDianTask} from '/@/api/case/index';
import { dateFormats, dateFormat,dateFormatTime, evidenceStatusName, getOutType, getEvidenceStatus } from '/@/common';
import { ElMessageBox, ElMessage } from 'element-plus';
import { deleteEvidence, GetyEvidenceTransferePager } from '/@/api/evidence/index';
import { GetTransfereEvidences } from '/@/api/evidence/transfere';
import { putRfids, queryImgs,checkImgs } from '/@/api/common/index';
import { sendPandian } from '/@/api/common/index';
import storeIndex from '/@/views/system/store/index.vue';
import { putEvidenceLocation } from '/@/api/evidence/index';
import { writeRfid } from '/@/api/hardware/index';
import { Session } from '/@/utils/storage';
export default defineComponent({
	name: 'unitEvidenceDetails',
	components: { CasePrint, EditCase, EditEvi, EviPrint, InInventory,ChangeInventory, OutInventory, ShowCase, storeIndex },
	activated() {
		this.init();
	},
	setup() {
		const router = useRouter();
		const store = useStore();
		const casePrintRef = ref();
		const editCaseRef = ref();
		const editEviRef = ref();
		const eviPrintRef = ref();
		const eviInRef = ref();
		const eviOutRef = ref();
		const eviChangeRef = ref();
		const InInventoryRef = ref();
		const ChangeInventoryRef = ref();
		const OutInventoryRef = ref();
		const caseid = router.currentRoute.value.query.caseid;
		const isSameOrgan = ref(false);//案件与当前登录人是否一致
		const state = reactive({
			screenHeight: document.body.clientHeight - 120,
			tableData: [],
			formInlineCase: {},
			formInlineEvi: {},
			tableLogData: [],
			title: '',
			selectionEvidences: [],
			refFormInlineCase: {},
			drawer: false,
			currentEviSt: -1 //当前案卷状态
		});
		const onPrintCaseInfo = () => {
			casePrintRef.value.openDialog(state.formInlineCase);
		};
		const onEditCaseInfo = () => {
			Object.assign(state.refFormInlineCase, state.formInlineCase);
			editCaseRef.value.openDialog();
		};
		const onAddEvidenceInfo = () => {
			//-1
			editEviRef.value.openDialog({ evidenceId: -1 });
		};
		const onEditEvidenceInfo = (row: any) => {
			editEviRef.value.openDialog(row);
		};
		const view3D=(row:any)=>{
			let _url = row.xingHao;
			if(_url){
				if(!(_url.startsWith("http:") || _url.startsWith("https:")))
					_url = "http://"+_url;
				window.open(_url);
			}else{
				ElMessage({
					message: '未配置3D模型url地址',
					type: 'warning',
				});
			}
		}
		const onPrintEviInfo = () => {
			if (!verify(0)) return false;
			eviPrintRef.value.openDialog({
				list: state.selectionEvidences,
				title: state.formInlineCase.hostUserOrganName,
				caseName: state.formInlineCase.caseName,
				caseNo: state.formInlineCase.caseNo,
				inspectionNo: state.formInlineCase.inspectionNo,
			});
		};
		//入库
	async function onEviInInfo ()  {
			if (!verify(1)) return false;

			var imgsPar=new Array();

			for(var i=0;i<state.selectionEvidences.length;i++)
			{
				var vSlevi=state.selectionEvidences[i];
				imgsPar.push({Id:vSlevi.id,wzNo:vSlevi.no});
			}
			store.dispatch('customs/setCustoms', { selectionEvidences: state.selectionEvidences, formInlineCase: state.formInlineCase });
			router.push({ path: '/evidence/unit/in', query: { t: new Date().getTime() } });
			return;//不在检查是否有照片
			//照片检查
		     await checkImgs(imgsPar).then((res: any) => {
					if (res.success&&!res.data) {
						ElMessage({
							message: '请录入照片',
							type: 'warning',
						});
					return false;
					}
				   store.dispatch('customs/setCustoms', { selectionEvidences: state.selectionEvidences, formInlineCase: state.formInlineCase });
			       router.push({ path: '/evidence/unit/in', query: { t: new Date().getTime() } });
		     	});

		
		};
		//出库
		const onEviOutInfo = () => {
			if (!verify(2)) return false;
			const ids = state.selectionEvidences.map((x) => {
				return x.id;
			});
			checkEvidenceAuditState({ ids: ids, ty: '出库' }).then((res: any) => {
				if (res.success) {
					for (var i = 0; i < state.selectionEvidences.length; i++) {
						var r1 = state.selectionEvidences[i];
						if (res.data.indexOf(r1.id) == -1) {
							ElMessage({
								message: '案卷：' + r1.name + '，未出库审批。',
								type: 'warning',
							});
							return;
						}
					}
					store.dispatch('customs/setCustoms', { selectionEvidences: state.selectionEvidences, formInlineCase: state.formInlineCase });
					router.push({ path: '/evidence/unit/out', query: { t: new Date().getTime() } });
				} else {
					ElMessage({
						message: '操作成功',
						type: 'warning',
					});
				}
			});
		};
		const { proxy } = getCurrentInstance() as any;
		//更换位置
		const onEviChangeInfo = () => {
			if (!verify(2)) return false;
			state.drawer = true;
			proxy.mittBus.off('changeLocation');
			proxy.mittBus.on('changeLocation', (data: any) => {
				putEvidenceLocation({
					LocationCode: data.code,
					LocationId: data.id,
					LocationName: data.name,
					EvidenceIds: state.selectionEvidences.map((x) => {
						return x.id;
					}),
				}).then((res: any) => {
					if (res.success) {
						ElMessage({ message: '操作成功', type: 'success' });
						//更新成功，刷新数据
						state.drawer = false;
						proxy.mittBus.off('changeLocation');
						//刷新当前物语操作记录
						rowClick(state.selectionEvidences[0]).then(function(){
							//打开第一条记录
							onLink(state.tableLogData[0],true);
						});
					}
				});
			});
		};
		//入库清单
		const onInventoryInfo = async (row: any) => {
			let _type = 11;
			if (row.status == 1) _type = 10;
			await Promise.all([queryImgs(row.deliveryNo, _type), GetTransfereEvidences(row.id)]).then((res: any) => {
				const _imgs = res[0].data;
				const _data = res[1];
				const _transfereInfo = _data.data[0];
				const saveSignImg = _imgs.find((x) => x.type == 6)?.url;
				const signImg = _imgs.find((x) => x.type == 4 || x.type == 5)?.url;
				const data = {
					formInlineCase: state.formInlineCase,
					row: _data.data,
					transfereInfo: _transfereInfo,
					deliveryNo: row.deliveryNo,
					saveSignImg: saveSignImg,
					signImg: signImg,
				};
				
				if (row.status == 1) {
					if(row.deliveryDicType==7)
					{
						ChangeInventoryRef.value.openDialog(data);
						return;
					}
					InInventoryRef.value.openDialog(data);
				} else {
					OutInventoryRef.value.openDialog(data);
				}
			});
		};
		//照片，凭证
		const onEviImgInfo = (ty, obj: any) => {
			let title = '案卷';
			if (ty == 3) title = '凭证';
			router.getRoutes().find((x) => x.name == 'evidenceImg').meta.title = `${title}照片`;
			router.getRoutes().find((x) => x.name == 'evidenceImg').title = `${title}照片`;
			router.push({
				path: '/evidence/unit/img',
				query: {
					id: 0,
					ty: ty,
					name: obj.name,
					no: ty == 3 ? obj.deliveryNo : obj.no,
					isSameOrgan:isSameOrgan.value?"1":""
				},
			});
		};

		const onUploadFile = (ty, obj: any) => {
			router.push({
				path: '/evidence/unit/attachfile',
				query: {
					caseid: caseid,
					caseName: state.formInlineCase.caseName,
					evidenceName: obj ? obj.name : '',
					evidenceId: obj ? obj.id : '',
					isSameOrgan:isSameOrgan.value?"1":"",
					fff:new Date().getTime()
				},
			});
		};

		async function init() {
			await getCaseEvidence(caseid).then((res: any) => {
				if (res.success) {
					Object.assign(state.formInlineCase, res.data);
					isSameOrgan.value = (res.data.organId == Session.get('userInfo')?.organId);
					state.tableData = res.data.evidences;
				}
			});
		}
		async function rowClick(row) {
			state.tableLogData = [];
			state.title = `${row.name} [${row.no ?? ''}] 流转记录`;
			state.currentEviSt = row.status;
			return GetyEvidenceTransferePager({
				PageSize: 10000,
				EvidenceId: row.id,
			}).then((res: any) => {
				if (res.success) {
					state.tableLogData = res.data.data;
				}
			});
		}
		async function handleEvidenceSelectionChange(val) {
			state.selectionEvidences = val;
		}
		async function onDelete() {
			if (!verify()) return false;
			await ElMessageBox.confirm('是否刪除?')
				.then(() => {
					const ids = state.selectionEvidences.map((x) => {
						return x.id;
					});
					deleteEvidence({ ids: ids }).then((res: any) => {
						if (res.success) {
							ElMessage({
								message: '操作成功',
								type: 'success',
							});
							init();
						}
					});
				})
				.catch(() => {});
		}

		 function verify(type) {
			if (state.selectionEvidences.length < 1) {
				ElMessage({
					message: '请选择案卷',
					type: 'warning',
				});
				return false;
			}
			if (type == 1) {
				if (state.selectionEvidences.some((x) => x.status == 1)) {
					ElMessage({
						message: '状态不匹配，只能操作登记或者出库的案卷',
						type: 'warning',
					});
					return false;
				}

			}
			if (type == 2) {
				if (state.selectionEvidences.some((x) => x.status != 1)) {
					ElMessage({
						message: '状态不匹配，只能操作入库的案卷',
						type: 'warning',
					});
					return false;
				}
			}
			return true;
		}

		function onReaderInfo(data) {
			store.dispatch('hardware/getHardwareConfigByKey', 'yjpz_dukaqi').then(function (cfg) {
				if (!cfg || !cfg.res1) {
					ElMessage('未配置【发卡器配置】');
					return;
				}

				var epc = '000' + new Date().valueOf()+'00000000';
				writeRfid({ Epc: epc, key: cfg.res1 }).then((resResult) => {
					//console.log(resResult);
					if (resResult.data.Success) {
						ElMessage({ message: '读取成功', type: 'success' });
						putRfids({ list: [{ id: data.id, rfid: epc }] }).then((resl) => {
							if (resl.success) {
								init();
								ElMessage({ message: '存储成功', type: 'success' });
							} else {
								ElMessage.error('已经绑定其他案卷，无法再次绑定');
							}
						});
					} else {
						ElMessage.error('读取失败');
					}
				});
			});
		}
		async function onLink(row: any,showinventory:boolean) {
			let _type = 0;
			if (row.status == 1) _type = 10;
			if (row.status == 2) _type = 11;
			await Promise.all([queryImgs(row.deliveryNo, _type), GetTransfereEvidences(row.id)]).then((res) => {
				const _data = res[1];
				row.imgs = res[0].data;
				row.saveSignImg = row.imgs.find((x) => x.type == 6)?.url;
				row.signImg = row.imgs.find((x) => x.type == 4 || x.type == 5)?.url;
				store.dispatch('customs/setCustoms', {
					selectionEvidences: _data.data.map((x: any) => {
						return {
							no: x.evidenceNo,
							name: x.evidenceName,
							quantity: x.evidenceQuntity,
							source: x.source,
							extractionParts: x.extractionParts,
							extractionPersonName: x.extractionPersonName,
							extractionDateTime: x.extractionDateTime,
							extractMethod: x.extractMethod,
							status: x.status,
							location: x.location,
							cabinetCode: x.cabinetCode,
							beforeLocation:x.beforeLocation,
							evidenceShape: x.evidenceShape,
							transfereNo: x.transfereNo,
						};
					}),
					transfereInfo: row,
					formInlineCase: state.formInlineCase,
					deliveryNo: row.deliveryNo,
					showinventory:showinventory
				});
				if (row.status == 1) {
					router.push({ path: '/evidence/unit/inDetails', query: { t: new Date().getTime() } });
				} else {
					router.push({ path: '/evidence/unit/outDetails', query: { t: new Date().getTime() } });
				}
			});
		}

		function getRand(min, max) {
			var rand = Math.random();
			return Math.round(min + rand * (max - min));
		}

		async function pandian() {
			var num = getRand(100000, 999999);
			var taskdata = new Array();
			for (var i = 0; i < state.tableData.length; i++) {
				var _data = state.tableData[i];
				if (_data.rfid || _data.no) {
					taskdata.push({ evid: _data.id ,evidenceName: _data.name, address: _data.location, epc: _data.rfid || _data.no, registerState: 1 });
				}
			}
			if(taskdata.length == 0){
				ElMessage({
					message: '无可盘点案卷！',
					type: 'warning',
				});
				return;
			}
			pandianForMR730(taskdata);
			return;
			var data = { taskId: num, taskName: num + '盘点计划', type: 0, taskData: taskdata };

			await sendPandian(JSON.stringify(data)).then((res) => {
				var _result = JSON.parse(res.data);
				if (res.success && _result.success) {
					ElMessage({ message: num + '盘点计划,发送成功', type: 'success' });
				} else {
					ElMessage.error(_result.message);
				}
			});
		}
		async function pandianForMR730(taskdata) {
			var ids = taskdata.map(function(a){ return a.evid;});

			ElMessageBox.prompt('请输入盘点计划名称：', '盘点', {
				confirmButtonText: '确定',
				cancelButtonText: '取消'
			}).then(({ value }) => {
				if(value){
					var data = { name: value, ids: ids };
					savePanDianTask(JSON.stringify(data)).then((res) => {
						if (res.success) {
							ElMessage({ message: '盘点计划,添加成功', type: 'success' });
						} else {
							ElMessage.error(res.msg);
						}
					});
				}
			}).catch(() => {
				//取消
			}); 
		}
		onUnmounted(() => {});
		return {
			pandian,
			onReaderInfo,
			dateFormatTime,
			store,
			casePrintRef,
			editCaseRef,
			editEviRef,
			eviPrintRef,
			eviInRef,
			eviOutRef,
			eviChangeRef,
			InInventoryRef,
			ChangeInventoryRef,
			OutInventoryRef,
			onPrintCaseInfo,
			onEditCaseInfo,
			onEditEvidenceInfo,
			view3D,
			onAddEvidenceInfo,
			onPrintEviInfo,
			onEviInInfo,
			checkImgs,
			onEviOutInfo,
			onEviChangeInfo,
			onInventoryInfo,
			onEviImgInfo,
			onUploadFile,
			dateFormats,
			dateFormat,
			caseid,
			init,
			rowClick,
			handleEvidenceSelectionChange,
			evidenceStatusName,
			onDelete,
			getOutType,
			getEvidenceStatus,
			onLink,
			...toRefs(state),
			isSameOrgan
		};
	},
});
</script>
